package com.guo.autoscan.ssh2;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;

public class SSHCommandExecutor
{
    private String ipAddress;
    private String username;
    private String password;
    public static final int DEFAULT_SSH_PORT = 22;
    private Vector<String> stdout;

    public SSHCommandExecutor(String ipAddress, String username, String password)
    {
        this.ipAddress = ipAddress;
        this.username = username;
        this.password = password;
        this.stdout = new Vector();
    }

    public int execute(String command)
    {
        int returnCode = 0;
        JSch jsch = new JSch();
        MyUserInfo userInfo = new MyUserInfo();
        try
        {
            Session session = jsch.getSession(this.username, this.ipAddress, 22);
            session.setPassword(this.password);
            session.setUserInfo(userInfo);
            session.connect();


            Channel channel = session.openChannel("exec");
            ((ChannelExec)channel).setCommand(command);

            channel.setInputStream(null);

            BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));

            channel.connect();
            System.out.println("The remote command is: " + command);
            String line;
            while ((line = input.readLine()) != null)
            {
                System.out.println(line);
                this.stdout.add(line);
            }
            input.close();
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }
            channel.disconnect();
            session.disconnect();
        }
        catch (JSchException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return returnCode;
    }

    public Vector<String> getStandardOutput()
    {
        return this.stdout;
    }
}
